package 线程池案例;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

//线程池
class MyThreadPool {
    //阻塞队列
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    //最大线程数目
    private int ThreadMaxCount = 5;
    //提交任务
    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }
    //构造方法
    public MyThreadPool() {
        for(int i = 0; i < 5; i++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true) {
                        try {
                            //不断取出任务并运行
                            queue.take().run();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            t.start();
        }
    }
}


public class Test5 {
    public static void main(String[] arsg) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool();
        for(int i = 0; i < 100; i++) {
            int k = i;
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程:" +
                            Thread.currentThread().getName() + "完成了任务:" + k);
                }
            });
        }
    }
}
